package com.tianze.library.utils;

import android.content.Context;
import android.content.res.Resources;
import android.util.TypedValue;

/**
 * 单位转换工具类
 */
public class UnitUtils {

    private UnitUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * dp转px
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources()
                                                                                          .getDisplayMetrics());
    }

    /**
     * dp转px,不需要Context
     */
    public static int dp2px(float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, Resources.getSystem()
                                                                                            .getDisplayMetrics());
    }

    /**
     * sp转px
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources()
                                                                                         .getDisplayMetrics());
    }

    /**
     * sp转px,不需要上下文
     */
    public static int sp2px(float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, Resources.getSystem()
                                                                                           .getDisplayMetrics());
    }

    /**
     * px转dp
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxVal / scale + 0.5f);
    }

    /**
     * px转dp,不需要上下文
     */
    public static float px2dp(float pxVal) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (pxVal / scale + 0.5f);
    }

    /**
     * px转sp
     */
    public static float px2sp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxVal / scale + 0.5f);
    }

    /**
     * px转sp,不需要上下文
     */
    public static float px2sp(float pxVal) {
        final float scale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (pxVal / scale + 0.5f);
    }

}
